package cn._2dland.uploader.utils;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

@SuppressWarnings("unchecked")
public class ChannelUtils {
	private static Map<String, String> defMap = new HashMap<String, String>();
	private static Map<String, Map<String, String>> channelMap = new HashMap<String, Map<String,String>>();

	static {
		// 读取频道信息
		String home = System.getProperty("user.dir");
		String fileSep = System.getProperty("file.separator");
		if(!home.endsWith(fileSep))
			home += fileSep;
		try {
			String xmlFile = home + "channels.xml";
			// 解析XML
			SAXReader sax = new SAXReader();
			Document doc = sax.read(new File(xmlFile));
			Element root = doc.getRootElement();

			List<Element> sets = root.elements("set");
			for(Element set : sets) {
				String type = set.attributeValue("type");
				String defaultChannel = set.attributeValue("default");
				
				// 存储默认选项
				defMap.put(type, defaultChannel);
				
				// 存储频道列表
				Map<String, String> entry = new HashMap<String, String>();
				List<Element> channels = set.elements("channel");
				for(Element channel : channels) {
					entry.put(channel.attributeValue("id"), channel.getText());
				}
				channelMap.put(type, entry);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取获取频道名称
	 * @param type 类型
	 * @param id 频道ID
	 * @return
	 */
	public static String getNameByID(String type, String id) {
		Map<String, String> entry = channelMap.get(type);
		if(entry == null) return "未知";

		String channelID = entry.containsKey(id) ? id : defMap.get(type);
		String channelName = entry.get(channelID);
		if(channelName == null) channelName = "未知";

		return channelName;
	}
}
